package com.zhenyi.youqu.core;

import java.util.Date;

import org.joda.time.DateTime;

import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.youqu.common.model.YqApp;
import com.youqu.common.model.YqGroup;
import com.youqu.common.model.YqOrder;
import com.youqu.common.model.YqOrderInfo;
import com.youqu.common.model.YqProduct;
import com.youqu.common.model.YqProductGroup;
import com.youqu.common.model.YqUser;
import com.youqu.common.model.YqUserOrderGroup;

public class YQGroupPayUtils extends YQMiniAppController {

	/**
	 * 是否已能参团
	 * 
	 * @param product
	 * @return
	 */
	private boolean canJoinedGroup(YqProduct product, Long userId, Long groupId) {
		Long productId = product.getId();
		YqGroup joinedGroup = YqGroup.dao.findJoinedGroup(userId, productId);
		if (joinedGroup != null) {
			renderFailure("已加入团购");
			return false;
		}
		if (groupId != null) {
			// 添加团购成员
			YqUserOrderGroup userOrderGroup = YqUserOrderGroup.dao.findById(groupId, userId);
			if (userOrderGroup != null) {
				Long orderId = userOrderGroup.getOrderId();
				if (orderId != null) {
					YqOrder order = YqOrder.dao.findById(orderId);
					if (order != null) {
						if (order.getStatus().equals(YqOrder.STATUS_PAID)) {
							LogKit.warn("已支付团!! " + groupId + " " + userId + " " + productId);
							renderFailure("已支付团");
							return false;
						}
					}
				}
			}
			YqGroup group = YqGroup.dao.findById(groupId);
			if (group == null) {
				renderFailure("参团失败");
				return false;
			}
			group.updateGroupUserCount();
			if (group.getIsClosed().equals(1)) {
				renderFailure("已结束拼团");
				return false;
			}
			if (group.getIsDone().equals(1)) {
				renderFailure("拼团已完成");
				return false;
			}
			if (group.getExpire().getTime() <= new Date().getTime()) {
				renderFailure("拼团已超时");
				return false;
			}
		}
		return true;
	}

	/**
	 * 当前订单是否能支付(暂时停止直接重复支付功能)
	 * 
	 * @param order
	 * @return
	 */
	private boolean canPay(YqOrder order) {
		order.updateOrderStatus();
		if (order.getStatus().equals(YqOrder.STATUS_NOTPAY)) {
			if (new Date().getTime() <= order.getExpires().getTime()) {
				renderPay(order);
				return true;
			} else {
				order.closeOrder();
				LogKit.info("订单超时,重新下单");
			}
		} else {
			LogKit.info("非未支付订单");
		}
		return false;
	}

	/**
	 * 团购支付接口
	 */
	public void groupPay() {
		YqUser user = getUser();
		Long userId = user.getId();

		Long productGroupId = getParaToLong("productGroup");
		if (productGroupId == null) {
			LogKit.info("productGroupId null");
			renderError(404);
			return;
		}
		YqProductGroup productGroup = YqProductGroup.dao.findById(1);
		if (productGroup == null) {
			LogKit.info("productGroup null");
			renderError(404);
			return;
		}
		/**
		 * 通过orderId支付
		 */
		Long payOrderId = getParaToLong("orderId");
		if (payOrderId != null) {
			YqOrder order = YqOrder.dao.findById(payOrderId);
			if (order == null) {
				renderError(404);
				return;
			}
			order.updateOrderStatus();
			if (canPay(order)) {
				return;
			} else {
				renderFailure("订单已失效");
				return;
			}
		}
		Long productId = productGroup.getProductId();
		Long groupId = getParaToLong("groupId");
		YqProduct product = YqProduct.dao.findById(productId);
		if (product == null) {
			LogKit.info("product null");
			renderError(404);
			return;
		}
		boolean isGroup = product.getIsGroup().equals(1);
		if (!isGroup) {
			renderFailure("not group");
			return;
		}
		String nationalCode = getPara("nationalCode", "");
		String telNumber = getPara("telNumber", "");
		String cityName = getPara("cityName", "");
		String postalCode = getPara("postalCode", "");
		String detailInfo = getPara("detailInfo", "");
		String provinceName = getPara("provinceName", "");
		String userName = getPara("userName", "");
		String countyName = getPara("countyName", "");
		int count = getParaToInt("count", 1);
		String size = getPara("size", "");
		String remark = getPara("remark", "");
		Long formatId = getParaToLong("formatId");
		String extraInfo = getPara("extraInfo");

		if (product.getStorage() < count) {
			LogKit.info("productId:" + product.getId() + " 库存不足 - storage:" + product.getStorage() + " count:" + count);
			renderFailure("库存不足");
			return;
		}

		if (isGroup) {
			if (!canJoinedGroup(product, userId, groupId)) {
				return;
			}
		}

		YqApp app = getApp();
		YqOrder order = new YqOrder(app);
		order.setOutTradeNo(YqOrder.genTradeNo());
		int totalFee = productGroup.getPrice() * 100 * count;

		order.setTotalFee(String.valueOf(totalFee));
		// order.setAppId(APP_ID);
		// order.setMchId(PARTNER);
		order.setBody(product.getTitle());
		String openid = user.getOpenId();
		order.setOpenid(openid);
		order.save();
		String outTradeNo = YqOrder.genTradeNo() + YqOrder.MIN_HASHID.encode(order.getId());
		order.setOutTradeNo(outTradeNo);
		order.update();
		Long shopId = product.getShopId();
		boolean pushFlag = order.pushOrder(IpKit.getRealIpV2(getRequest()), shopId);
		if (!pushFlag) {
			renderFailure("下单失败");
			return;
		}

		order.setUserId(userId);
		order.update();

		YqOrderInfo newOrderInfo = new YqOrderInfo();
		// newOrderInfo.setType(YqOrder.TYPE_PRODUCT);
		newOrderInfo.setName(userName);
		newOrderInfo.setMobile(telNumber);
		newOrderInfo.setAddress(provinceName + cityName + countyName + detailInfo);
		newOrderInfo.setCount(count);
		newOrderInfo.setPostalCode(postalCode);
		newOrderInfo.setNationalCode(nationalCode);
		newOrderInfo.setRemark(remark);
		newOrderInfo.setSize(size);
		newOrderInfo.setFormatId(formatId);
		newOrderInfo.setExtraInfo(extraInfo);

		if (isGroup) {
			if (!EN_MUTI_PAY_GROUP) {
				SqlPara paidGrpupPara = db.getSqlPara("YQPaidGroup", Kv.by("userId", userId));
				if (YqGroup.dao.findFirst(paidGrpupPara) != null) {
					renderFailure("请勿重复购买");
					return;
				}
			}
			if (groupId == null) {
				// YqGroup group = YqGroup.dao.findBy(userId, productId);
				// if (group != null) {
				// if (group.getIsDone().equals(1)) {
				// renderFailure("拼团已成功");
				// return;
				// }
				// if (group.getIsClosed().equals(1)) {
				// renderFailure("拼团已关闭");
				// return;
				// }
				// if (group.getExpire().getTime() <= new Date().getTime()) {
				// renderFailure("拼团已超时");
				// return;
				// }
				// }
				YqGroup group = null;
				// 如果没有团,生成团
				if (group == null) {
					group = new YqGroup();
					group.setUserId(userId);
					group.setProductId(productId);

					Date expire = new DateTime().plusHours(productGroup.getGroupHours()).toDate();
					group.setExpire(expire);
					group.setCount(productGroup.getGroupCount());
					group.save();
				}
				groupId = group.getId();
			}
			// 添加团购成员
			YqUserOrderGroup userOrderGroup = YqUserOrderGroup.dao.findById(groupId, userId);
			if (userOrderGroup == null) {
				userOrderGroup = new YqUserOrderGroup();
				userOrderGroup.setUserId(userId);
				userOrderGroup.setGroupId(groupId);
				userOrderGroup.setOrderId(order.getId());
				userOrderGroup.save();
			} else {
				userOrderGroup.setOrderId(order.getId());
				userOrderGroup.update();
			}
			order.setData("groupId:" + groupId);
			order.setType(YqOrder.TYPE_GROUP);

			newOrderInfo.setType(YqOrder.TYPE_GROUP);
			newOrderInfo.setGroupId(groupId);
			newOrderInfo.setIsGroup(1);
		} else {
			order.setData("productId:" + productId);
		}
		Long orderId = order.getId();
		newOrderInfo.setIsNeedTrack(product.getIsNeedTrack());
		newOrderInfo.setProductId(productId);
		newOrderInfo.setOrderId(orderId);
		newOrderInfo.setTitle(product.getTitle());
		newOrderInfo.setCover(product.getCover());
		newOrderInfo.setIntro("");
		newOrderInfo.setPrice(String.valueOf(productGroup.getPrice()));
		newOrderInfo.setUserId(userId);
		newOrderInfo.setRefId(productId);
		String code = HASHID.encode(orderId);
		newOrderInfo.setHashId(code);
		// String qrcodeImageUrl = "http://qr.liantu.com/api.php?text=" + code;
		String qrcodeImageUrl = "http://release.zhen-yee.com/api/qrcode?text=" + code;
		newOrderInfo.setQrcode(qrcodeImageUrl);
		newOrderInfo.setCardType(product.getCardType());
		if (product.getCardType().equals(1)) { // 次卡
			newOrderInfo.setUseLimit(product.getCardUseLimit());
			newOrderInfo.setIsCard(1);
		} else if (product.getCardType().equals(2)) { // 日卡
			newOrderInfo.setCardAvailableDay(product.getCardAvailableDay());
			newOrderInfo.setIsCard(1);
		} else if (product.getCardType().equals(3)) { // 过期卡
			newOrderInfo.setCardExpire(product.getCardExpire());
			newOrderInfo.setIsCard(1);
		}
		newOrderInfo.save();
		order.update();
		product.setStorage(product.getStorage() - count);
		product.update();
		renderPay(order);
	}
}
